const crossSpawn = require('cross-spawn');
const childProcess = require('child_process');
const spawn = crossSpawn.sync;
const chalk = require('chalk');
const red = chalk.red;
const green = chalk.green;
const fs = require('fs-extra');
const { resolve } = require('path');
const currentPath = process.cwd().replace(/\\/g, '/') + '/';
function isWindows() {
  if (typeof process === 'undefined' || !process) {
    return false;
  }
  return process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys';
}
/**
 * 
 * @param {function} callback  回调函数
 * @param {string} moduleName 模块名称
 */
function downloadByGit(moduleName, callback) {
  console.log(green('start download'));
  fs.remove(`${currentPath}/juggle`, function(err) {
    if (err) return console.error(err)
    const result = spawn(
      'git',
      ['clone', `https://gitee.com/sonimei/juggle.git`],
      { stdio: 'inherit' }
    );
    const error = result.error;
    if (error) {
      console.log(red(error));
      return;
    }
    fs.remove(`${currentPath}/juggle/.git`,function(err){
      fs.copy(`${currentPath}/juggle`, currentPath, function(err) {
          if (err) return console.error(err)
          fs.remove(`${currentPath}/juggle`, ()=>{
            reviseFile(moduleName)
            callback && callback();
          })
      });
    })
  })
}


function publishCode() {
  console.log("检查git版本");
  return new Promise((resolve,reject)=>{
    const nowBranch = childProcess.execSync('git rev-parse --abbrev-ref HEAD').toString().replace(/\s+/, '')
    const branchList= childProcess.execSync('git branch -a').toString();

    /**
     * 必须是daily 分支才能发布
     */
    if(nowBranch.includes("daily")){
      // 已经存在正式分支
      if(branchList.includes(nowBranch.replace("daily/", "publish/"))){
        console.log("已经存在正式分支，请切换分支");
      }else{
        childProcess.execSync('git push origin ' + nowBranch)
        resolve()
      }
    }else{
      console.log("必须是daily 分支才能发布");
    }
  })
}

// 启动webpack

function webpackStart() {
  const data = childProcess.execSync('npm run build');
  console.log(data.toString())
}
/**
 * 修改下载后的文件，保证模块名称等于 package.json
 */
function reviseFile (moduleName) {
  console.log(chalk.green("正在重置项目名"));
  // 目前只修改了 打包后的文件名称
  let data = fs.readFileSync(currentPath + '/src/build.js',"utf-8")
  fs.writeFileSync(currentPath + '/src/build.js', data.replace("pmodFeedV3", moduleName), "utf-8");
  console.log(chalk.green("重置完成"));
}

/**
 * 判断一个文件夹是不是空的
 * @param {path} dirname 
 * @return Boolean
 */
function isEmptyDir(dirname){
  try{
      fs.rmdirSync(dirname)
  }
  catch(err){
      return false;
  }
  fs.mkdirSync(dirname);
  return true
}
/**
 * 把一个字符串换成驼峰的
 * @param {string} str 
 */
function changeName (str){
  var reg = /-(\w)/g;
  return str.replace(reg,function($,$1){
    return $1.toUpperCase();
  });
}

// 重命名gitClone下来的文件为项目文件名
async function renameFile() {
  // const oldPath = currentPath + tempName;
  // const nowPath = currentPath + projectName;
  // try {
  //   await fs.rename(oldPath, nowPath);
  //   unrelatedFileRemove(nowPath);
  // } catch (error) {
  //   console.error(red(error));
  // }
  console.log(green("正在修改文件名"));
}
/**
 * 
 * @param {string} color 颜色 red green 还有’‘
 * @param {string} text 输出文字
 */
async function log(color, text) {
  switch(color){
    case 'read':
      console.log(chalk.red(text));
      break;
    case 'green':
      console.log(chalk.green(text));
      break;
    default:
      console.log(text);
      break;
  }
}

module.exports = {
  downloadByGit,
  isWindows,
  currentPath,
  isEmptyDir,
  changeName,
  log,
  publishCode,
  webpackStart
};